{% extends "base.html" %}

{% block title %}农田管理{% endblock %}

{% block page_title %}农田管理{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css">
<style>
.field-management {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 20px;
    height: calc(100vh - 100px);
}

.field-list {
    background: white;
    padding: 20px;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    overflow-y: auto;
}

.field-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.field-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
}

.field-card h3 {
    color: var(--secondary-color);
    margin-bottom: 10px;
}

.field-info {
    margin-bottom: 10px;
}

.field-info p {
    margin: 5px 0;
    color: var(--text-color);
}

.field-actions {
    display: flex;
    gap: 10px;
}

#map-container {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    position: relative;
    height: 100%;
    min-height: 500px;
}

#map {
    height: 100%;
    width: 100%;
    border-radius: var(--border-radius);
    z-index: 1;
}

.map-controls {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    background: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.area-info {
    position: absolute;
    bottom: 20px;
    left: 20px;
    z-index: 1000;
    background: white;
    padding: 10px 15px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    font-size: 14px;
}

/* 添加农田标签样式 */
.field-label {
    background: none;
    border: none;
}

.field-label div {
    background: white;
    padding: 5px 10px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    font-size: 12px;
    white-space: nowrap;
}
</style>
{% endblock %}

{% block content %}
<div class="field-management">
    <div class="field-list">
        <div class="field-header">
            <h2>农田列表</h2>
            <button class="btn btn-primary" onclick="startAddField()">
                <i class="fas fa-plus"></i> 添加农田
            </button>
        </div>
        {% for field in fields %}
        <div class="field-card" data-field-id="{{ field.id }}">
            <h3>{{ field.name }}</h3>
            <div class="field-info">
                <p><i class="fas fa-ruler-combined"></i> 面积：{{ field.area }} 亩</p>
                <p><i class="fas fa-seedling"></i> 当前作物：{{ field.current_crop }}</p>
            </div>
            <div class="field-actions">
                <button class="btn btn-primary" onclick="showFieldOnMap({{ field.id }})">
                    <i class="fas fa-map-marker-alt"></i> 查看位置
                </button>
                <button class="btn btn-secondary" onclick="editField({{ field.id }})">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-danger" onclick="deleteField({{ field.id }})">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </div>
        </div>
        {% endfor %}
    </div>
    
    <div id="map-container">
        <div id="map-loading" style="
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
            background: white;
            padding: 10px 20px;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        ">
            <i class="fas fa-spinner fa-spin"></i> 加载地图中...
        </div>
        <div id="map"></div>
        <div class="map-controls">
            <button class="btn btn-primary" onclick="startDrawing()"
                title="点击开始绘制农田边界，单击添加顶点，双击完成绘制"
            >
                <i class="fas fa-draw-polygon"></i> 绘制农田
            </button>
            <button class="btn btn-secondary" onclick="clearDrawing()"
                title="清除当前绘制的边界"
            >
                <i class="fas fa-eraser"></i> 清除
            </button>
        </div>
        <div class="area-info" style="display: none;">
            <span>面积：<span id="area-value">0</span> 亩</span>
        </div>
    </div>
</div>

<!-- 添加农田模态框 -->
<div id="add-field-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-plus"></i> 添加农田</h2>
        </div>
        <form id="add-field-form">
            <div class="form-group">
                <label>农田名称</label>
                <input type="text" name="name" required>
            </div>
            <div class="form-group">
                <label>当前作物</label>
                <input type="text" name="current_crop">
            </div>
            <input type="hidden" name="area" id="field-area">
            <input type="hidden" name="boundary" id="field-boundary">
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideAddFieldModal()">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    保存
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 编辑农田模态框 -->
<div id="edit-field-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-edit"></i> 编辑农田</h2>
        </div>
        <form id="edit-field-form" onsubmit="updateField(event)">
            <div class="form-group">
                <label>农田名称</label>
                <input type="text" name="name" required>
            </div>
            <div class="form-group">
                <label>当前作物</label>
                <input type="text" name="current_crop">
            </div>
            <input type="hidden" name="field_id">
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideEditFieldModal()">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    保存
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
<script src="https://unpkg.com/leaflet-geometryutil@0.10.1/src/leaflet.geometryutil.js"></script>
<script>
let map, drawControl, drawnItems;
let currentPolygon = null;
let fieldPolygons = {};  // 存储农田多边形
let isAddingField = false;  // 是否正在添加农田

// 等待所有资源加载完成后初始化地图
window.addEventListener('load', function() {
    // 隐藏加载提示
    const loadingEl = document.getElementById('map-loading');
    if (loadingEl) {
        loadingEl.style.display = 'none';
    }
    
    // 初始化地图
    initMap();
});

// 初始化地图
function initMap() {
    try {
        // 等待 DOM 加载完成
        if (!document.getElementById('map')) {
            console.error('Map container not found');
            return;
        }
        
        // 初始化地图，设置默认视图为新疆大学位置
        map = L.map('map', {
            center: [43.7940, 87.6278],
            zoom: 13,
            minZoom: 3,
            maxZoom: 18,
            zoomControl: false  // 禁用默认缩放控制
        });
        
        // 添加地图图层
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
            maxZoom: 18,
            tileSize: 256,
            subdomains: ['a', 'b', 'c']  // 使用多个子域名加快加载
        }).addTo(map);
        
        // 添加缩放控制
        L.control.zoom({
            position: 'topright'
        }).addTo(map);
        
        // 初始化绘图图层
        drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);
        
        // 配置绘图控件选项
        drawControl = new L.Control.Draw({
            draw: {
                polygon: {
                    allowIntersection: false,
                    showArea: true,
                    shapeOptions: {
                        color: '#3388ff',
                        weight: 2,
                        opacity: 1,
                        fillOpacity: 0.2
                    },
                    metric: false,  // 使用非公制单位
                    feet: false,    // 不使用英尺
                    nautic: false,  // 不使用海里
                    precision: {
                        km: 2,
                        ha: 2,
                        m: 0,
                        mi: 2,
                        ac: 2
                    }
                },
                // 禁用其他绘图工具
                circle: false,
                rectangle: false,
                circlemarker: false,
                marker: false,
                polyline: false
            },
            edit: {
                featureGroup: drawnItems,
                poly: {
                    allowIntersection: false
                },
                edit: {
                    selectedPathOptions: {
                        maintainColor: true,
                        moveMarkers: true
                    }
                }
            }
        });
        
        // 添加绘图控件到地图
        map.addControl(drawControl);
        
        // 监听绘制完成事件
        map.on('draw:created', function(e) {
            const layer = e.layer;
            
            // 计算面积
            const area = calculateArea(layer);
            
            // 保存当前多边形
            if (currentPolygon) {
                map.removeLayer(currentPolygon);
            }
            currentPolygon = layer;
            
            // 添加到绘图图层
            drawnItems.addLayer(layer);
            
            // 更新表单数据
            const coordinates = layer.getLatLngs()[0].map(latlng => [latlng.lat, latlng.lng]);
            document.getElementById('field-area').value = area;
            document.getElementById('field-boundary').value = JSON.stringify(coordinates);
            
            // 显示面积信息
            document.getElementById('area-value').textContent = area;
            document.querySelector('.area-info').style.display = 'block';
        });
        
        // 监听编辑完成事件
        map.on('draw:edited', function(e) {
            const layers = e.layers;
            layers.eachLayer(function(layer) {
                // 更新面积显示
                const area = calculateArea(layer);
                document.getElementById('area-value').textContent = area;
                
                // 更新表单数据
                const coordinates = layer.getLatLngs()[0].map(latlng => [latlng.lat, latlng.lng]);
                document.getElementById('field-area').value = area;
                document.getElementById('field-boundary').value = JSON.stringify(coordinates);
            });
        });
        
        // 加载所有农田边界
        loadFieldBoundaries();
        
        // 监听地图缩放事件，调整标签大小
        map.on('zoomend', function() {
            const zoom = map.getZoom();
            document.querySelectorAll('.field-label div').forEach(label => {
                // 根据缩放级别调整字体大小
                const fontSize = Math.max(10, Math.min(16, zoom - 8));
                label.style.fontSize = `${fontSize}px`;
                // 调整标签透明度
                label.style.opacity = zoom < 12 ? '0' : '1';
            });
        });
        
        // 监听地图事件
        map.on('zoomend moveend', function() {
            // 保存当前地图状态
            const center = map.getCenter();
            const zoom = map.getZoom();
            localStorage.setItem('mapState', JSON.stringify({
                center: [center.lat, center.lng],
                zoom: zoom
            }));
        });
        
        // 恢复上次的地图状态
        try {
            const savedState = localStorage.getItem('mapState');
            if (savedState) {
                const state = JSON.parse(savedState);
                map.setView(state.center, state.zoom);
            }
        } catch (error) {
            console.error('Error restoring map state:', error);
        }
    } catch (error) {
        console.error('Error initializing map:', error);
        const loadingEl = document.getElementById('map-loading');
        if (loadingEl) {
            loadingEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> 地图加载失败，请刷新页面重试';
            loadingEl.style.color = 'red';
        }
    }
}

// 加载农田边界
function loadFieldBoundaries() {
    // 清除现有的农田边界
    Object.values(fieldPolygons).forEach(polygon => {
        if (polygon) {
            map.removeLayer(polygon);
        }
    });
    fieldPolygons = {};
    drawnItems.clearLayers();
    
    {% for field in fields %}
    {% if field['boundary'] and field['boundary']|length >= 3 %}
        try {
            const boundary = {{ field['boundary']|tojson }};
            
            // 创建多边形
            const polygon = L.polygon(boundary, {
                color: '#3388ff',
                weight: 2,
                opacity: 1,
                fillOpacity: 0.2,
                fillColor: '#3388ff'
            }).addTo(map);
            
            // 添加标签
            const center = polygon.getBounds().getCenter();
            const label = L.divIcon({
                className: 'field-label',
                html: '<div>' + {{ field['name']|tojson|safe }} + '</div>',
                iconSize: [0, 0],  // 让标签自适应内容大小
                iconAnchor: [0, 0],  // 设置标签锚点
                className: 'field-label'  // 使用自定义样式
            });
            
            // 添加标签到地图
            const marker = L.marker(center, { 
                icon: label,
                interactive: false,  // 禁用标签的交互
                keyboard: false     // 禁用键盘操作
            }).addTo(map);
            
            // 存储多边形引用
            fieldPolygons[{{ field['id'] }}] = polygon;
            
            // 将所有农田的边界添加到一个图层组
            drawnItems.addLayer(polygon);
            
            // 为多边形添加点击事件
            polygon.on('click', function() {
                showFieldOnMap({{ field['id'] }});
            });
            
            // 添加悬停效果
            polygon.on('mouseover', function() {
                polygon.setStyle({
                    fillOpacity: 0.4,
                    weight: 3
                });
            });
            
            polygon.on('mouseout', function() {
                polygon.setStyle({
                    fillOpacity: 0.2,
                    weight: 2
                });
            });
            
        } catch (error) {
            console.error('Error loading field boundary:', error);
        }
    {% endif %}
    {% endfor %}
    
    // 如果有农田，调整地图视图以显示所有农田
    if (Object.keys(fieldPolygons).length > 0) {
        const bounds = Object.values(fieldPolygons).map(p => p.getBounds());
        const allBounds = L.latLngBounds(bounds);
        map.fitBounds(allBounds, {
            padding: [50, 50],
            maxZoom: 16,
            animate: true,
            duration: 1
        });
    } else {
        // 如果没有农田，显示默认视图（新疆大学位置）
        map.setView([43.7940, 87.6278], 13);
    }
}

// 显示指定农田
function showFieldOnMap(fieldId) {
    const polygon = fieldPolygons[fieldId];
    if (polygon) {
        // 取消当前的编辑状态
        if (currentPolygon && currentPolygon.editing) {
            currentPolygon.editing.disable();
        }
        
        // 清除之前的高亮效果
        Object.values(fieldPolygons).forEach(p => {
            p.setStyle({
                color: '#3388ff',
                fillOpacity: 0.2
            });
        });
        
        // 平滑地将地图中心移动到农田位置
        map.flyToBounds(polygon.getBounds(), {
            padding: [50, 50],
            duration: 1.5,
            easeLinearity: 0.5
        });
        
        // 高亮显示选中的农田
        polygon.setStyle({
            color: '#ff3388',
            fillOpacity: 0.4
        });
        
        // 3秒后恢复原样式
        setTimeout(() => {
            polygon.setStyle({
                color: '#3388ff',
                fillOpacity: 0.2
            });
        }, 3000);
    } else {
        alert('该农田暂无边界数据，请先编辑农田并绘制边界');
    }
}

// 编辑农田
async function editField(fieldId) {
    const button = event.target.closest('button');
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 加载中...';
    
    try {
        const field = await fetch(`/api/fields/${fieldId}`).then(r => r.json());
        if (!field) {
            alert('获取农田信息失败');
            return;
        }
        
        // 清除当前的编辑状态
        if (currentPolygon) {
            map.removeLayer(currentPolygon);
            currentPolygon = null;
        }
        
        // 显示编辑模态框
        document.getElementById('edit-field-modal').style.display = 'block';
        
        // 填充表单
        const form = document.getElementById('edit-field-form');
        form.querySelector('[name="name"]').value = field.name;
        form.querySelector('[name="current_crop"]').value = field.current_crop;
        form.querySelector('[name="field_id"]').value = field.id;
        
        // 在地图上显示边界
        if (field.boundary && field.boundary.length > 0) {
            currentPolygon = L.polygon(field.boundary).addTo(map);
            drawnItems.addLayer(currentPolygon);
            map.fitBounds(currentPolygon.getBounds());
            
            // 启用编辑模式
            currentPolygon.editing.enable();
            
            // 更新面积显示
            const area = calculateArea(currentPolygon);
            document.getElementById('area-value').textContent = area;
            document.querySelector('.area-info').style.display = 'block';
        } else {
            alert('该农田暂无边界数据，请重新绘制');
            startDrawing();
        }
    } catch (error) {
        console.error('编辑农田失败:', error);
        alert('获取农田信息失败');
    } finally {
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-edit"></i> 编辑';
    }
}

// 更新农田信息
async function updateField(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const fieldId = formData.get('field_id');
    
    let fieldBoundary = [];
    let area = 0;
    if (currentPolygon) {
        fieldBoundary = currentPolygon.getLatLngs()[0].map(latlng => [latlng.lat, latlng.lng]);
        area = calculateArea(currentPolygon);
    }
    
    const data = {
        name: formData.get('name'),
        current_crop: formData.get('current_crop'),
        area: parseFloat(area),
        boundary: fieldBoundary
    };
    
    try {
        const response = await fetch(`/api/fields/${fieldId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            const error = await response.json();
            alert(error.error || '更新农田失败');
        }
    } catch (error) {
        alert('更新农田失败');
    }
}

// 开始绘制
function startDrawing() {
    if (currentPolygon) {
        map.removeLayer(currentPolygon);
    }
    try {
        new L.Draw.Polygon(map).enable();
    } catch (error) {
        console.error('启动绘图工具失败:', error);
        alert('启动绘图工具失败，请刷新页面重试');
    }
}

// 清除绘制
function clearDrawing() {
    if (currentPolygon) {
        map.removeLayer(currentPolygon);
        currentPolygon = null;
        // 清除表单数据
        document.getElementById('field-area').value = '';
        document.getElementById('field-boundary').value = '';
    }
    document.querySelector('.area-info').style.display = 'none';
}

// 计算面积（平方米转亩）
function calculateArea(polygon) {
    try {
        const latlngs = polygon.getLatLngs()[0];
        if (!latlngs || latlngs.length < 3) {
            console.error('Invalid polygon vertices');
            return 0;
        }
        let area = L.GeometryUtil.geodesicArea(latlngs);
        // 转换为亩，1亩 = 666.667平方米
        const mu = area / 666.667;
        return mu.toFixed(2);
    } catch (error) {
        console.error('Error calculating area:', error);
        return 0;
    }
}

// 表单提交处理
document.getElementById('add-field-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    if (!currentPolygon) {
        alert('请先在地图上绘制农田边界');
        return;
    }
    
    // 验证边界点数量
    const fieldBoundary = JSON.parse(document.getElementById('field-boundary').value);
    if (fieldBoundary.length < 3) {
        alert('农田边界至少需要3个点');
        return;
    }
    
    const formData = new FormData(e.target);
    const data = {
        name: formData.get('name'),
        current_crop: formData.get('current_crop'),
        area: parseFloat(formData.get('area')),
        boundary: fieldBoundary
    };
    
    try {
        const response = await fetch('/api/fields', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            const error = await response.json();
            alert(error.error || '添加农田失败');
        }
    } catch (error) {
        alert('添加农田失败');
    }
});

// 显示添加农田模态框
function showAddFieldModal() {
    document.getElementById('add-field-modal').style.display = 'block';
    // 清空表单
    document.getElementById('add-field-form').reset();
}

// 隐藏添加农田模态框
function hideAddFieldModal() {
    document.getElementById('add-field-modal').style.display = 'none';
    // 清除绘制的多边形
    if (currentPolygon) {
        map.removeLayer(currentPolygon);
        currentPolygon = null;
    }
    document.querySelector('.area-info').style.display = 'none';
    isAddingField = false;
}

// 开始添加农田
function startAddField() {
    isAddingField = true;
    startDrawing();
}

// 删除农田
async function deleteField(fieldId) {
    if (!confirm('确定要删除此农田吗？\n删除后将无法恢复，且相关的设备和任务也会被删除。')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/fields/${fieldId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            // 从地图上移除农田边界
            const polygon = fieldPolygons[fieldId];
            if (polygon) {
                map.removeLayer(polygon);
                delete fieldPolygons[fieldId];
            }
            // 移除农田卡片
            document.querySelector(`.field-card[data-field-id="${fieldId}"]`).remove();
        } else {
            const error = await response.json();
            alert(error.error || '删除农田失败');
        }
    } catch (error) {
        alert('删除农田失败');
    }
}

// 隐藏编辑农田模态框
function hideEditFieldModal() {
    document.getElementById('edit-field-modal').style.display = 'none';
    // 清除绘制的多边形
    if (currentPolygon) {
        map.removeLayer(currentPolygon);
        currentPolygon = null;
    }
    document.querySelector('.area-info').style.display = 'none';
}
</script>
{% endblock %} 